package com.teachoa.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.snaker.engine.SnakerEngine;
import org.snaker.engine.model.ProcessModel;
import org.snaker.engine.model.WorkModel;
import org.snaker.jfinal.plugin.SnakerPlugin;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.teachoa.util.L;
import com.teachoa.util.Maps;

@SuppressWarnings("rawtypes")
public class BaseController extends Controller {
	
	protected String success(String msg) {
		return JSON.toJSONString(Maps.newHashMap("msg", msg, "isSuccess", true));
	}
	
	protected String fail(String msg) {
		return JSON.toJSONString(Maps.newHashMap("msg", msg, "isSuccess", false));
	}
	
	protected Map<String, String> getParamMap() {
		Map<String, String[]> map = getParaMap();
		Map<String, String> newmap = new HashMap<String, String>();
		for(Map.Entry<String, String[]> entry:map.entrySet()) {
			newmap.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
		}
		return newmap;
	}
	
	protected String getCurrentUserId() {
		Map user = getSessionAttr("currentUser");
		return L.toString(user.get("id"));
	}
	
	protected int getCurrentUserType() {
		Map user = getSessionAttr("currentUser");
		return L.toInt(user.get("type"));
	}
	
	protected String getCurrentUserName() {
		Map user = getSessionAttr("currentUser");
		return L.toString(user.get("username"));
	}
	
	protected SnakerEngine getSnakerEngine() {
		return SnakerPlugin.getEngine();
	}

	protected int getProcessNodeByTaskName(String processId, String taskName) {
		ProcessModel pm = getSnakerEngine().process().getProcessById(processId).getModel();
		List<WorkModel> list = pm.getWorkModels();
		int index = 0;
		for(int i=0;i<list.size();i++) {
			if(list.get(i).getDisplayName().equals(taskName)) {
				index = i+2;break;
			}
		}
		return index;
	}
}
